<template>
  <div class="tldiv frcc" v-loading="isloading">
    <!-- <div class="countdiv">
      共:{{ marks1.data.length }}条;镶嵌线:<el-switch
        v-model="isshowxiangqianxian"
        size="small"
        active-text=""
        inactive-text=""
      />
    </div>
    <div class="nodatadiv frcc" v-if="marks1.data.length == 0 || marks1.data.length == 1">
      <span v-if="marks1.data.length == 0"> 暂无数据 </span>
      <span v-if="marks1.data.length == 1">
        一条数据无法展示时间轴:{{ marks1.marks[0] }}
      </span>
    </div> -->

    <div class="sldiv">

    </div>

    <div style="padding: 5px 10px 0px 5px">
      <img
        src="/yxrh/shijianzhou-zuo.png"
        style=""
        alt=""
        class="zuoyoudiv"
        @click="leftclick()"
      />
    </div>


    <vue-slider
      style="flex: 1"
      :min="min"
      :tooltip="'always'"
      :tooltip-formatter="formatter2"
      :max="max"
      v-model="tlval"
      :process="false"
      :marks="formatter2mark"
      :data="marks1.data"
      @change="timelinechange"
    >
      <template #dot="{ value, focus }">
        <div :class="['custom-dot', { focus }]">
          <img src="/yxrh/huakuai.png" alt="" class="huakuaidiv" />
        </div>
      </template>
    </vue-slider>

    <div style="padding: 5px 5px 0px 10px">
      <img
        src="/yxrh/shijianzhou-you.png"
        style=""
        alt=""
        class="zuoyoudiv"
        @click="rightclick"
      />
    </div>
  </div>
</template>
<script setup>
import VueSlider from "vue-slider-component";
import "vue-slider-component/theme/default.css";

import { ref, reactive, onMounted, watch, onUnmounted } from "vue";
import { ElMessage } from "element-plus";

import useCommon from "@/components/pages/yingxiangronghe/common/mixins/useCommon.js";
import { apiList } from "@/api/apiList";
import dayjs from "dayjs";

import _ from "lodash";

import { useEarthStore } from "@/stores/earth";

let tlval = ref(0);
let min = ref(0);
let max = ref(0);

let marks1 = reactive({
  data: [],
  marks: {},
  marks1: {},
  marks2: {},
});

let Common = useCommon();
let earthStore = useEarthStore();

function timelinechange(value, index) {
  // console.log(value, index);
}

const getViewExtend = () => {
  let params = {};
  let extend = viewer.camera.computeViewRectangle();
  if (typeof extend === "undefined") {
    //2D下会可能拾取不到坐标，extend返回undefined,因此作如下转换
    let canvas = viewer.scene.canvas;
    let upperLeft = new Cesium.Cartesian2(0, 0); //canvas左上角坐标转2d坐标
    let lowerRight = new Cesium.Cartesian2(canvas.clientWidth, canvas.clientHeight); //canvas右下角坐标转2d坐标

    let ellipsoid = viewer.scene.globe.ellipsoid;
    let upperLeft3 = viewer.camera.pickEllipsoid(upperLeft, ellipsoid); //2D转3D世界坐标

    let lowerRight3 = viewer.camera.pickEllipsoid(lowerRight, ellipsoid); //2D转3D世界坐标

    let upperLeftCartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(
      upperLeft3
    ); //3D世界坐标转弧度
    let lowerRightCartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(
      lowerRight3
    ); //3D世界坐标转弧度

    let minx = Cesium.Math.toDegrees(upperLeftCartographic.longitude); //弧度转经纬度
    let maxx = Cesium.Math.toDegrees(lowerRightCartographic.longitude); //弧度转经纬度

    let miny = Cesium.Math.toDegrees(lowerRightCartographic.latitude); //弧度转经纬度
    let maxy = Cesium.Math.toDegrees(upperLeftCartographic.latitude); //弧度转经纬度
    params.minx = minx;
    params.maxx = maxx;
    params.miny = miny;
    params.maxy = maxy;
  } else {
    //3D获取方式
    params.maxx = Cesium.Math.toDegrees(extend.east);
    params.maxy = Cesium.Math.toDegrees(extend.north);

    params.minx = Cesium.Math.toDegrees(extend.west);
    params.miny = Cesium.Math.toDegrees(extend.south);
  }
  // 返回屏幕所在经纬度范围
  return params;
};

// 获取当前地图瓦片级别
function tileLevel() {
  let tiles = new Set();
  let tilesToRender = viewer.scene.globe._surface._tilesToRender;
  if (Cesium.defined(tilesToRender)) {
    for (let i = 0; i < tilesToRender.length; i++) {
      tiles.add(tilesToRender[i].level);
    }
    return tiles;
  }
}

function getparams(params) {
  let level = tileLevel();
  level = Array.from(level)[0];
  let bbox = getViewExtend();
  bbox = [
    [bbox.minx, bbox.miny],
    [bbox.minx, bbox.maxy],
    [bbox.maxx, bbox.maxy],
    [bbox.maxx, bbox.miny],
    [bbox.minx, bbox.miny],
  ];
  let geojson = [
    bbox
      .map((item) => {
        return item.join(" ");
      })
      .join(","),
  ];
  return {
    level,
    geojson,
  };
}



// 监听相机事件

watch(tlval, (newVal, oldVal) => {
  let iitem = marks1.marks2[tlval.value];

  earthStore.timelinetime = '未获取到信息'
  if (iitem.lineId == '1111' || iitem.lineId == '2222') {
    return
  }
  
  earthStore.timelinetime = iitem.date
  Common.removeAll();
  Common.loadXYZ(iitem.date, iitem.lineId);
  if (isshowxiangqianxian.value) {
    iitem.lineId.split(",").map((iitem) => {
      Common.loadLine({ lineId: iitem });
    });
  }

  // Common.loadGeojson()
});

function leftclick(params) {
  let nowindex = 0;
  marks1.data.map((item, index) => {
    if (item == tlval.value) {
      nowindex = index;
    }
  });
  if (nowindex - 1 == -1) {
    return;
  }
  tlval.value = marks1.data[nowindex - 1];
}
function rightclick(params) {
  let nowindex = 0;
  marks1.data.map((item, index) => {
    if (item == tlval.value) {
      nowindex = index;
    }
  });
  if (nowindex + 1 == marks1.data.length) {
    return;
  }
  tlval.value = marks1.data[nowindex + 1];
  // tlval.value =
}

let formatter2 = (v) => `${marks1.marks1[v]}`;

let formatter2mark = (v) => {
  return {
    label: `${marks1.marks[v]}`,
    labelStyle: {
      // color: '#3498db'
    },
    // labelActiveStyle: {
    //   color: '#3498db'
    // }
  };
};

let resdata = [
  "2015-5-5",
  "2018-5-5",
  "2018-7-5",
  "2019-3-5",
  "2019-5-5",
  "2019-7-5",
  "2020-9-5",
  "2021-10-5",
  "2022-11-5",
  "2023-3-5",
  "2024-1-5",
];

onMounted(() => {
  moveend()
  cameraChange();
});

let camerahandler = {};

function cameraChange(params) {
  camerahandler = viewer.camera.changed.addEventListener(() => {

// console.log(viewer.camera.heading,viewer.camera.pitch,viewer.camera.roll);
    demoveend();
    // 当前高度
    // 下面可以写其他的代码了
  });
}

function cameraChangeDis(params) {
  camerahandler();
}

onUnmounted(() => {
  // dragEventDis()
  cameraChangeDis();
  Common.removeAll();
});

function genline(resdata) {
  marks1.data = [];
  marks1.marks = {};
  marks1.marks1 = {};
  marks1.marks2 = {};

  let tmpdata0 = {
    date: "1985-01-01",
    lineId: "1111"
  }

  dayjs().format("yyyy-MM-dd")


  let tmpdata1 = {
    date: dayjs().format("YYYY-MM-DD"),
    lineId: "2222"
  }

  if (resdata.length == 0) {
    resdata.push(tmpdata0);
    resdata.push(tmpdata1);
  }
  
  if (resdata.length == 1) {
    let tmpdata = resdata[0]
    resdata = []
    resdata.push(tmpdata0);
    resdata.push(tmpdata);
  }

  resdata.map((item, index) => {
    marks1.data.push(dayjs(item.date).diff(resdata[0].date, "day"));
    marks1.marks1[marks1.data[marks1.data.length - 1]] = item.date;
    marks1.marks2[marks1.data[marks1.data.length - 1]] = item;
    if (index == 0 || index == resdata.length - 1) {
      marks1.marks[marks1.data[marks1.data.length - 1]] = item.date.split("-")[0];
    } else {
      marks1.marks[marks1.data[marks1.data.length - 1]] = "";
    }
  });
  max.value = marks1.data[marks1.data.length - 1];
  tlval.value = marks1.data[marks1.data.length - 1];

  // ElMessage.success(JSON.stringify(marks1))
}

let isloading = ref(false);

let isshowxiangqianxian = ref(false);

function moveend() {
  console.log("移动结束");
  let sousuoparams = {
    timeRange: "", //时间范围（:分隔）
    sensor: "", //传感器（,分隔）
    wxName: "", //卫星名称
    sunCorner: "", //太阳角
    geojson: [], //矩形框四角点
    shpPath: "", //矢量文件导入
    level: "", //分辨率
  };

  let params = getparams();
  sousuoparams.level = params.level;
  sousuoparams.geojson = params.geojson;

  // // return
  isloading.value = true;
  apiList.getMapServerTimebase(params).then((res) => {
    console.log(res);
    isloading.value = false;
    // dataList.value = res.data;
    genline(res.data);
  });
}

let demoveend = _.debounce(moveend, 100);


</script>
<style lang="scss">
.vue-slider-ltr {
  height: 10px !important;
}
.vue-slider-mark {
  // background-color: #fff!important;
  // background-color: #67C23A!important;
  // width: 10px!important;
}
.vue-slider-mark-step {
  // background-color: #fff!important;
  background-color: #67c23a !important;
  border-radius: 0% !important;
  width: 6px !important;
}
.nodatadiv {
  position: absolute;
  background-color: #555;
  z-index: 1001;
  width: 100%;
  height: 100%;
  top: 0px;
}
.countdiv {
  position: absolute;
  bottom: 5px;
  z-index: 1002;
}
.zuoyoudiv {
  width: 15px;
  filter: invert(100%) brightness(550%);
  cursor: pointer;
}

.custom-dot {
  .huakuaidiv {
    position: absolute;
    width: 20px;
    cursor: pointer;
    top: -3px;
    left: -2px;
  }
}

.tldiv {
  width: 350px;
  height: 80px;
  padding: 5px 15px 0px 15px;
  user-select: none;
  .sldiv{
    position: absolute;
    width: 370px;
    height: 30px;
    border-radius: 10px;;
    background-color: #ddd4;
  }
}
</style>
